package com.lx.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听网站在线人数：也就是监听有多少个session
 */
public class OnlineCountListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent httpSessionEvent) {

        ServletContext context = httpSessionEvent.getSession().getServletContext();

        System.out.println("sessionId:" + httpSessionEvent.getSession().getId());

        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = new Integer(1);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count+1);
        }
        context.setAttribute("onlineCount", onlineCount);
    }

    /**
     * session过期
     * 1：手动注销  .getSession().invalidate();
     * 2: 自动注销  xml中进行配置<session-timeout>60</session-timeout>
     * @param httpSessionEvent
     */
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext context = httpSessionEvent.getSession().getServletContext();

        System.out.println("sessionId:" + httpSessionEvent.getSession().getId());

        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = new Integer(1);
        } else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count-1);
        }
        context.setAttribute("onlineCount", onlineCount);
    }
}
